package com.fengye.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author sunlei
 * @version 1.0
 * @date 2024/5/10 15:21:05
 * @description redis分布式锁工具类
 */
@Component
public class RedisLock {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 尝试获取锁
     *
     * @param lockKey   锁的key
     * @param value     锁的值
     * @param expire    过期时间
     * @param timeUnit  过期时间单位
     * @return 是否成功获取锁
     */
    public boolean tryLock(String lockKey, String value, long expire, TimeUnit timeUnit) {
        return redisTemplate.opsForValue().setIfAbsent(lockKey, value, expire, timeUnit);
    }
}
